package hidalgo.expenses.activity;

import hidalgo.expenses.R;
import hidalgo.expenses.adapter.TransactionAdapter;
import hidalgo.expenses.dao.TransactionDao;
import hidalgo.expenses.entities.Transaction;
import hidalgo.expenses.utils.HideAnimation;
import hidalgo.expenses.utils.Properties;
import hidalgo.expenses.widgets.ActionBar;

import java.util.ArrayList;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class TransactionsActivity extends BaseActivity {

	private ActionBar actionBar;

	private ListView transactionListView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.transactions_activity);

		transactionListView = (ListView) findViewById(R.id.transactionList);

		transactionListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Toast.makeText(TransactionsActivity.this,
						"transactionId :" + id, Toast.LENGTH_SHORT).show();

			}

		});

		setUpActionBar();

		Bundle extras = this.getIntent().getExtras();

		int accountId = extras.getInt("ACCOUNTID");

		populateTransactions(accountId);

	}

	private void populateTransactions(int accountId) {

		new AsyncTask<Integer, Void, ArrayList<Transaction>>() {

			protected void onPreExecute() {
				actionBar.showProgressBar();
				actionBar.getProgressBar().startLoading(
						Properties.progressBarSpeed);

			};

			@Override
			protected ArrayList<Transaction> doInBackground(Integer... params) {

				int accountId = params[0];

				return TransactionDao.getTransactionByAccount(accountId);
			}

			protected void onPostExecute(ArrayList<Transaction> transactionList) {

				if (transactionList != null) {

					TransactionAdapter transactionAdapter = new TransactionAdapter(
							TransactionsActivity.this,
							R.layout.transaction_item, transactionList);

					transactionListView.setAdapter(transactionAdapter);

				}

				actionBar.getProgressBar().completeLoading();
				actionBar.getProgressBar().startAnimation(
						new HideAnimation(1.0f, 1.0f, 1.0f, 0.0f, 500,
								actionBar.getProgressBar(), true));

			};

		}.execute(accountId);

	}

	private void setUpActionBar() {

		actionBar = (ActionBar) findViewById(R.id.actionBar);
		actionBar.setTitle("Transacciones");
		// set home icon that does nothing when the user clicks on it
		actionBar.setHomeLogo(R.drawable.ic_title_home_default,
				new OnClickListener() {
					public void onClick(View v) {
						TransactionsActivity.this.finish();
					}
				});
		
	}

}
